<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('close')"
    title="密码强度分析"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="analysis-container">
      <!-- 总体统计 -->
      <div class="summary-section">
        <h4>总体统计</h4>
        <div class="summary-cards">
          <div class="summary-card">
            <div class="card-title">总账号数</div>
            <div class="card-value">{{ totalAccounts }}</div>
          </div>
          <div class="summary-card weak">
            <div class="card-title">弱密码</div>
            <div class="card-value">{{ weakPasswords }}</div>
          </div>
          <div class="summary-card medium">
            <div class="card-title">中等密码</div>
            <div class="card-value">{{ mediumPasswords }}</div>
          </div>
          <div class="summary-card strong">
            <div class="card-title">强密码</div>
            <div class="card-value">{{ strongPasswords }}</div>
          </div>
        </div>
      </div>

      <!-- 密码强度分布图 -->
      <div class="chart-section">
        <h4>密码强度分布</h4>
        <div class="strength-chart">
          <div class="chart-bar">
            <div class="bar-segment weak" :style="{ width: weakPercentage + '%' }">
              <span v-if="weakPercentage > 15">弱 {{ weakPercentage }}%</span>
            </div>
            <div class="bar-segment medium" :style="{ width: mediumPercentage + '%' }">
              <span v-if="mediumPercentage > 15">中 {{ mediumPercentage }}%</span>
            </div>
            <div class="bar-segment strong" :style="{ width: strongPercentage + '%' }">
              <span v-if="strongPercentage > 15">强 {{ strongPercentage }}%</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 详细列表 -->
      <div class="details-section">
        <h4>详细分析</h4>
        <div class="filter-tabs">
          <el-radio-group v-model="activeFilter" @change="filterAccounts">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="weak">弱密码</el-radio-button>
            <el-radio-button label="medium">中等密码</el-radio-button>
            <el-radio-button label="strong">强密码</el-radio-button>
          </el-radio-group>
        </div>

        <div class="accounts-list">
          <div
            v-for="account in filteredAccounts"
            :key="account.id"
            class="account-item"
          >
            <div class="account-info">
              <div class="account-name">{{ account.name }}</div>
              <div class="account-username">{{ account.username }}</div>
            </div>
            <div class="strength-info">
              <div class="strength-bar">
                <div 
                  class="strength-fill" 
                  :class="getStrengthClass(account.strengthScore)"
                  :style="{ width: (account.strengthScore * 25) + '%' }"
                ></div>
              </div>
              <div class="strength-text" :class="getStrengthClass(account.strengthScore)">
                {{ getStrengthText(account.strengthScore) }}
              </div>
            </div>
            <div class="strength-details">
              <el-button 
                size="small" 
                type="text" 
                @click="showDetails(account)"
              >
                详情
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('close')">关闭</el-button>
        <el-button type="primary" @click="exportReport">导出报告</el-button>
      </div>
    </template>

    <!-- 密码详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="密码详情"
      width="500px"
      append-to-body
    >
      <div v-if="selectedAccount" class="password-details">
        <div class="detail-item">
          <label>账号名称：</label>
          <span>{{ selectedAccount.name }}</span>
        </div>
        <div class="detail-item">
          <label>用户名：</label>
          <span>{{ selectedAccount.username }}</span>
        </div>
        <div class="detail-item">
          <label>密码长度：</label>
          <span>{{ selectedAccount.password.length }} 位</span>
        </div>
        <div class="detail-item">
          <label>强度评分：</label>
          <span>{{ selectedAccount.strengthScore }}/4</span>
        </div>
        <div class="detail-item">
          <label>安全建议：</label>
          <div class="suggestions">
            <div 
              v-for="suggestion in selectedAccount.suggestions" 
              :key="suggestion"
              class="suggestion-item"
            >
              • {{ suggestion }}
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useAccountsStore } from '../stores/accounts'
import { ElMessage } from 'element-plus'
import zxcvbn from 'zxcvbn'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close'])

const accountsStore = useAccountsStore()
const activeFilter = ref('all')
const showDetailDialog = ref(false)
const selectedAccount = ref(null)
const analyzedAccounts = ref([])

// 分析所有账号的密码强度
const analyzePasswords = () => {
  analyzedAccounts.value = accountsStore.accounts.map(account => {
    const result = zxcvbn(account.password)
    const suggestions = generateSuggestions(account.password, result)
    
    return {
      ...account,
      strengthScore: result.score,
      crackTime: result.crack_times_display.offline_slow_hashing_1e4_per_second,
      suggestions
    }
  })
}

// 生成安全建议
const generateSuggestions = (password, zxcvbnResult) => {
  const suggestions = []
  
  if (password.length < 12) {
    suggestions.push('建议密码长度至少12位')
  }
  
  if (!/[A-Z]/.test(password)) {
    suggestions.push('建议包含大写字母')
  }
  
  if (!/[a-z]/.test(password)) {
    suggestions.push('建议包含小写字母')
  }
  
  if (!/[0-9]/.test(password)) {
    suggestions.push('建议包含数字')
  }
  
  if (!/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
    suggestions.push('建议包含特殊字符')
  }
  
  if (zxcvbnResult.feedback.suggestions.length > 0) {
    suggestions.push(...zxcvbnResult.feedback.suggestions)
  }
  
  if (suggestions.length === 0) {
    suggestions.push('密码强度良好')
  }
  
  return suggestions
}

// 计算统计数据
const totalAccounts = computed(() => analyzedAccounts.value.length)
const weakPasswords = computed(() => analyzedAccounts.value.filter(a => a.strengthScore <= 1).length)
const mediumPasswords = computed(() => analyzedAccounts.value.filter(a => a.strengthScore === 2 || a.strengthScore === 3).length)
const strongPasswords = computed(() => analyzedAccounts.value.filter(a => a.strengthScore === 4).length)

const weakPercentage = computed(() => totalAccounts.value ? Math.round((weakPasswords.value / totalAccounts.value) * 100) : 0)
const mediumPercentage = computed(() => totalAccounts.value ? Math.round((mediumPasswords.value / totalAccounts.value) * 100) : 0)
const strongPercentage = computed(() => totalAccounts.value ? Math.round((strongPasswords.value / totalAccounts.value) * 100) : 0)

// 过滤账号
const filteredAccounts = computed(() => {
  switch (activeFilter.value) {
    case 'weak':
      return analyzedAccounts.value.filter(a => a.strengthScore <= 1)
    case 'medium':
      return analyzedAccounts.value.filter(a => a.strengthScore === 2 || a.strengthScore === 3)
    case 'strong':
      return analyzedAccounts.value.filter(a => a.strengthScore === 4)
    default:
      return analyzedAccounts.value
  }
})

// 获取强度样式类
const getStrengthClass = (score) => {
  if (score <= 1) return 'weak'
  if (score <= 3) return 'medium'
  return 'strong'
}

// 获取强度文本
const getStrengthText = (score) => {
  if (score <= 1) return '弱'
  if (score <= 3) return '中等'
  return '强'
}

// 显示详情
const showDetails = (account) => {
  selectedAccount.value = account
  showDetailDialog.value = true
}

// 导出报告
const exportReport = () => {
  const report = {
    date: new Date().toLocaleString(),
    totalAccounts: totalAccounts.value,
    weakPasswords: weakPasswords.value,
    mediumPasswords: mediumPasswords.value,
    strongPasswords: strongPasswords.value,
    accounts: analyzedAccounts.value.map(account => ({
      name: account.name,
      username: account.username,
      strengthScore: account.strengthScore,
      strengthText: getStrengthText(account.strengthScore),
      suggestions: account.suggestions
    }))
  }
  
  const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `密码强度分析报告_${new Date().toISOString().split('T')[0]}.json`
  a.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('报告导出成功')
}

// 过滤账号
const filterAccounts = () => {
  // 触发重新计算
}

// 监听visible变化，当对话框打开时分析密码
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    analyzePasswords()
  }
}, { immediate: true })

onMounted(() => {
  if (props.visible) {
    analyzePasswords()
  }
})
</script>

<style scoped>
.analysis-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.summary-section h4,
.chart-section h4,
.details-section h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.summary-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.summary-card {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  border: 2px solid transparent;
}

.summary-card.weak {
  border-color: #f56565;
  background: #fed7d7;
}

.summary-card.medium {
  border-color: #ed8936;
  background: #feebc8;
}

.summary-card.strong {
  border-color: #48bb78;
  background: #c6f6d5;
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.strength-chart {
  height: 60px;
  background: #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
}

.chart-bar {
  display: flex;
  height: 100%;
}

.bar-segment {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 14px;
  transition: all 0.3s ease;
}

.bar-segment.weak {
  background: #f56565;
}

.bar-segment.medium {
  background: #ed8936;
}

.bar-segment.strong {
  background: #48bb78;
}

.filter-tabs {
  margin-bottom: 16px;
}

.accounts-list {
  max-height: 300px;
  overflow-y: auto;
}

.account-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  margin-bottom: 8px;
  background: white;
}

.account-info {
  flex: 1;
  min-width: 0;
}

.account-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.account-username {
  font-size: 12px;
  color: #666;
}

.strength-info {
  flex: 1;
  margin: 0 16px;
}

.strength-bar {
  width: 100%;
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 4px;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
}

.strength-fill.weak {
  background: #f56565;
}

.strength-fill.medium {
  background: #ed8936;
}

.strength-fill.strong {
  background: #48bb78;
}

.strength-text {
  font-size: 12px;
  font-weight: 500;
}

.strength-text.weak {
  color: #f56565;
}

.strength-text.medium {
  color: #ed8936;
}

.strength-text.strong {
  color: #48bb78;
}

.strength-details {
  flex-shrink: 0;
}

.password-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.detail-item label {
  font-weight: 500;
  color: #333;
  min-width: 80px;
}

.suggestions {
  flex: 1;
}

.suggestion-item {
  margin-bottom: 4px;
  color: #666;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
